<?php
/*
 * @Author: 李明
 * @Date: 2021-08-17 09:07:02
 * @LastEditTime: 2022-01-30 14:00:40
 * @LastEditors: 李明
 * @Description:
 * @FilePath: /CRM2.0-PHP/app/Http/Controllers/order/OrderController.php
 * @山东壹零贰肆信息科技有限公司
 */

namespace App\Http\Controllers\order;

use App\Http\Controllers\admin\BranchController;
use App\Http\Controllers\common\CommonFun;
use App\Http\Controllers\common\LMReturn;
use App\Models\Branch;
use App\Models\WorkerBranch;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Resources\Order as ResourcesOrder;
use App\Http\Resources\OrderV2;
use App\Models\InterestRecord;
use App\Models\Order;
use App\Models\Product;
use App\Models\User;
use App\Models\Worker;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Utils;
use App\Http\Controllers\Documents\utils as docutils;
use App\Models\Image;
use App\Http\Resources\Order\OrderDetail;
use App\Models\BankCard;
use App\Models\FamiliesMoneyRecord;

class OrderController extends Controller
{
    /**
     * @description: 生成订单接口
     * @param {Request} $request
     * @return {*}
     */
    public function OrderSave(Request $request)
    {
        /*数据接收部分*/
        try {
            //去验证token值
            $tokenInfo = json_decode($this->verifyTokenLm(), true);
            //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
            if ($tokenInfo['code'] == 400) {
                return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
            }
            $worker_id = $tokenInfo['worker_id'];
            //接收前端传递过来的值
            $all = $request->all();
            $record_worker_id = $all['record_worker_id'] ?? $worker_id;
            $order_wokrer_id = $all['worker_id'] ?? $worker_id;
            $contract_no = $all['contract_no'] ?? '';
            $user_id = $all['user_id'];
            $product_id = $all['product_id'] ?? '';
            $valid_time = $all['valid_time'] ?? '';
            $sign_time = $all['sign_time'] ?? '';
            $order_money = $all['order_money']; // 订单金额
            // $investment_way = $all['investment_way'] ?? ''; // 支付方式 1银行转账  2pos刷卡 3微信 4支付宝 5现金
            $investment_way = $all['investment_way'] ?? 1;        // 投资状态  1常规  2通联待付款 3通联已付款
            if ($investment_way == 3) {
                $investment_way = 2;
            }
            $pay_list = $all['pay_list'] ?? []; // 到账银行部分
            if ($investment_way != 1) { // 如果是通联
                if (count($pay_list) > 1) {
                    LMReturn::Error('无法生成订单，通联付款时，不允许存在多种付款方式', 'NOCCO16');
                }
                if ($pay_list[0]['pay_type'] != 4) { // 1银行转账  2pos刷卡  3转存  4通联 5公对私  6公对公
                    LMReturn::Error('无法生成订单，通联付款时，不允许存在其他付款方式', 'NOCCO17');
                }
            }
            $audit_step = '1'; // 审核步骤  只能是1
            $bank_card_id = $all['bank_card_id'];
            if (BankCard::find($bank_card_id)->user_id != $user_id) {
                LMReturn::Error('无法生成订单，银行卡和员工不匹配', 'NOCCO1');
            }
            $image_ids = $all['image_ids'] ?? [];
            $remark = $all['remark'] ?? '';
            $is_first_instance = $all['is_first_instance'] ?? '3'; // 审核状态    1通过  2拒绝 3待审核
            $order_status = $all['order_status'] ?? '2';
            $order_status = $order_status == 2 ? $order_status : '-1'; // 生成订单时   订单状态只允许有 -1草稿和2审核中  两个状态，如果不是2 就把他改成-1
            // $branch = WorkerBranch::where('worker_id', $order_wokrer_id)->first();
            $branches = Worker::find($order_wokrer_id)->branches;
            if (count($branches) != 1) {
                return LMReturn::Error('该员工部门数据存在异常，请联系运营排查', 'NOCCO2');
            } else { // 部门只能绑定到客户经理的部门
                $branch_id = $branches[0]->id;
            }
            $renewal_contract_number = $all['renewal_contract_number'] ?? ''; // 续约老合同号
            // 首先判断是否已经存在 合同编号，存在不允许继续添加
            $order_old_list = Order::where("contract_no", $all['contract_no'])->get();
            if (count($order_old_list) > 0) {
                return LMReturn::Error('您输入的合同编号和现有合同编号冲突', 'NOCCO3');
            }
        } catch (\Throwable $th) {
            return LMReturn::Error('请检查参数是否正确', 'NOCCO4');
        }
        /*数据处理部分*/
        try {

            $user = User::find($user_id);
            if ($user == null) {
                return LMReturn::Error('客户存在问题，请检查', 'OCOS1');
            }
            if ($renewal_contract_number == '') { // 正常订单
                $renewal_contract_number = null;
                $old_order_id = null;
                $id_number = $user->id_number;
                $id_num_user_list = User::where('id_number', $id_number)
                    ->get();
                $id_num_user_id_list = CommonFun::id_list_model($id_num_user_list);
                $order_list = Order::whereIn("user_id", $id_num_user_id_list)->get();
                $is_first = count($order_list) > 0 ? '2' : '1'; // 是否为首个订单  1是新单 2否存量 3转续
            } else { // 转续订单
                $renewal_order_list = Order::where('contract_no', $renewal_contract_number)->get();
                if (count($renewal_order_list) > 0) {
                    $is_first = '3'; // 是否为首个订单  1是新单 2否存量 3转续
                } else {
                    return LMReturn::Error('无法进行转存，不存在历史订单，如有疑问，请联系管理员', 'NOCCO5');
                }
                if (isset($all['order_id'])) {
                    $old_order_id = $all['order_id'];
                } else {
                    return LMReturn::Error('未传入原合同id', 'NOCCO6');
                }
                $old_order = Order::find($old_order_id);
                if ($user->id_number != $old_order->user->id_number) {
                    return LMReturn::Error('转存失败，订单主体不可变', 'NOCCO7');
                }
            }
            if ($product_id == '' || $valid_time == '' || $sign_time == '') {
                return LMReturn::Error('请检查产品\生效时间\签约时间', 'NOCCO8');
            }
            $product = Product::find($product_id);
            if ($product == null) {
                return LMReturn::Error('产品存在问题，请检查', 'OCOS1');
            }
            $moneyQT = $product->money; // 起投金额
            $moneySX = $product->ceiling; // 可投上限
            if ($order_money <= 0) {
                return LMReturn::Error('订单金额错误', 'NOCCO9');
            }
            if ($order_money < $moneyQT) { //5万（包含）-50万
                return LMReturn::Error('低于产品起投金额', 'NOCCO10');
            }
            if ($order_money > $moneySX && $moneySX != 0) {
                return LMReturn::Error('大于产品可投上限', 'NOCCO11');
            }
            //计算产品相关数据
            $product_data = OrderController::calculateEndTime($valid_time, $product, $order_money);
            $contract_end_date = $product_data['contract_end_date']; // 合同结束日期
            $contract_end_date_int = strtotime($contract_end_date); // 合同结束日期的时间戳
            $valid_time_int = strtotime($valid_time); // 生效日期的时间戳
            if ($contract_end_date_int < $valid_time_int) {
                return LMReturn::Error('发生了不可预知的错误,请检查参数，如果无法解决，请联系技术支持', 'NOCCO12');
            }
            $results_rate = $product_data['results_rate'];
            $results_money = $product_data['results_money'];
        } catch (\Throwable $th) {
            return LMReturn::Error('网络错误，数据处理出现问题', 'NOCCO13');
        }
        /*数据入库部分*/
        try {
            DB::beginTransaction(); //开启事务
            $order = Order::create(
                [
                    'contract_no' => $contract_no,
                    'renewal_contract_number' => $renewal_contract_number,
                    'order_id' => $old_order_id,
                    'user_id' => $user_id,
                    'worker_id' => $order_wokrer_id,
                    'product_id' => $product_id,
                    'branch_id' => $branch_id,
                    'bank_card_id' => $bank_card_id,
                    'order_status' => $order_status,
                    'is_first' => $is_first,
                    'audit_step' => $audit_step,
                    'is_first_instance' => $is_first_instance,
                    'record_worker_id' => $record_worker_id,
                    'results_rate' => $results_rate,
                    'order_money' => $order_money,
                    'results_money' => $results_money,
                    'remark' => $remark,
                    'contract_end_date' => $contract_end_date,
                    'sign_time' => $sign_time,
                    'valid_time' => $valid_time,
                    'investment_way' => $investment_way,
                    'fdd_sign_status' => 2,
                    'contract_file' => 2,
                ]
            );
            $order_id = $order->id;
            // 根据传入的branch去查找下级部门的管理员
            $worker_manager_list = [];
            $workers = Worker::where('id', $order_wokrer_id)->with('roles')->first();
            if (count($workers['roles']) != 0) {
                $worker_manager_dic['name'] = $workers['name'];
                $worker_manager_dic['role'] = $workers['roles'][0]['id'];
                $worker_manager_list[] = $worker_manager_dic;
            }
            //用于存上级的。
            $in_branch = Branch::where('id', $branch_id)->with('manage_workers.roles')->first();
            foreach ($in_branch['manage_workers'] as $manager) {
                if (count($manager['roles']) != 0 && count($workers['roles']) != 0) {
                    if ($manager['id'] != $order_wokrer_id && $manager['roles'][0]['id'] != $workers['roles'][0]['id']) {
                        $manager_dic['name'] = $manager['name'];
                        $manager_dic['role'] = $manager['roles'][0]['id'];
                        $worker_manager_list[] = $manager_dic;
                    }
                }
            }
            if (env('COMPANY') == 3) { // 国邦盛世
                if ($in_branch['pid'] != 0) {
                    $worker_manager_list = Utils::getPBranch($in_branch['pid'], []);
                }
                $list_count = count($worker_manager_list);
                if ($list_count == 1) {
                    $order->vice_president_id = $in_branch['name'];
                    $order->president_id = $worker_manager_list[0];
                } elseif ($list_count == 2) {
                    $order->regional_manage_id = $in_branch['name'];
                    $order->vice_president_id = $worker_manager_list[0];
                    $order->president_id = $worker_manager_list[1];
                } elseif ($list_count == 3) {
                    $order->department_manage_id = $in_branch['name'];
                    $order->regional_manage_id = $worker_manager_list[0];
                    $order->vice_president_id = $worker_manager_list[1];
                    $order->president_id = $worker_manager_list[2];
                } elseif ($list_count == 4) {
                    $order->sales_manage_id = $in_branch['name'];
                    $order->department_manage_id = $worker_manager_list[0];
                    $order->regional_manage_id = $worker_manager_list[1];
                    $order->vice_president_id = $worker_manager_list[2];
                    $order->president_id = $worker_manager_list[3];
                } elseif ($list_count == 5) {
                    $order->group_manage_id = $in_branch['name'];
                    $order->sales_manage_id = $worker_manager_list[0];
                    $order->department_manage_id = $worker_manager_list[1];
                    $order->regional_manage_id = $worker_manager_list[2];
                    $order->vice_president_id = $worker_manager_list[3];
                    $order->president_id = $worker_manager_list[4];
                } elseif ($list_count == 6) {
                    $order->wealth_manage_id = $in_branch['name'];
                    $order->group_manage_id = $worker_manager_list[0];
                    $order->sales_manage_id = $worker_manager_list[1];
                    $order->department_manage_id = $worker_manager_list[2];
                    $order->regional_manage_id = $worker_manager_list[3];
                    $order->vice_president_id = $worker_manager_list[4];
                    $order->president_id = $worker_manager_list[5];
                } elseif ($list_count == 7) {
                    $order->wealth_manage_id = $worker_manager_list[0];
                    $order->group_manage_id = $worker_manager_list[1];
                    $order->sales_manage_id = $worker_manager_list[2];
                    $order->department_manage_id = $worker_manager_list[3];
                    $order->regional_manage_id = $worker_manager_list[4];
                    $order->vice_president_id = $worker_manager_list[5];
                    $order->president_id = $worker_manager_list[6];
                }
            } elseif (env('COMPANY') == 2) { // 锦程
                if ($in_branch['pid'] != 0) {
                    $worker_manager_list = Utils::getBranchManager($in_branch['pid'], $worker_manager_list);
                }
                foreach ($worker_manager_list as $worker_dic) {
                    if ($worker_dic['role'] == 44) {
                        $order->wealth_manage_id = $worker_dic['name'];
                    } elseif ($worker_dic['role'] == 33) {
                        $order->group_manage_id = $worker_dic['name'];
                    } elseif ($worker_dic['role'] == 32) {
                        $order->sales_manage_id = $worker_dic['name'];
                    } elseif ($worker_dic['role'] == 31) {
                        $order->department_manage_id = $worker_dic['name'];
                    } elseif ($worker_dic['role'] == 30) {
                        $order->regional_manage_id = $worker_dic['name'];
                    } elseif ($worker_dic['role'] == 29) {
                        $order->vice_president_id = $worker_dic['name'];
                    }
                }
            }
            //生成订单编号
            $strNum = str_pad(mt_rand(10000, 19999), 5, '0', STR_PAD_LEFT);
            if ($order_id < 10000) {
                $strOrderID = str_pad($order_id, 5, '0', STR_PAD_LEFT);
            } else {
                $strOrderID = $order_id;
            }
            $nowTime = time();
            $order_no = $strNum . $nowTime . $strOrderID;
            $order->order_no = $order_no;
            $order->results_rate = $product->results_rate;
            $order->results_money = $order->results_rate * $order->order_money / 100;
            $order->save();
            //在记录表里面去添加
            OrderRecordController::InsertOrderModelRecord($order, $tokenInfo, '2');
            OrderController::OrderPayList($pay_list, $order, 1, 1);
            DB::commit(); //提交至数据库
        } catch (\Throwable $th) {
            DB::rollback(); //数据库回滚
            return LMReturn::Error('网络错误，入库失败', 'NOCCO14');
        }
        //图片处理 如果返回false，则是修改时报错，数据库回滚，返回错误信息
        if (!Utils::UpImage($image_ids, $order->images, $order_id, 3, $worker_id)) {
            return LMReturn::Error('添加修改图片出现错误,其他信息已提交，请重新上传图片', 'NOCCO15');
        }
        $order['product_name'] = $order->product->name;
        $order['user_name'] = $order->user->name;
        return LMReturn::Success($order, '订单成功添加');
    }
    /**
     * @description: 外层一定要有事务，没有的话自己加   循环添加  订单的到账记录
     * @param {*} $pay_list
     * @param {*} $order
     * @param string $type 1订单收款 2还本付息 3费用报销
     * @param string $status 1审核中  2通过/待打款  3拒绝 4打款中 5已收款(已付款)
     * @return {*}
     */
    public static function OrderPayList($pay_list, $order, $type = '1', $status = '1')
    {
        $order_id = $order->id;
        $where = [];
        $where[] = ['order_id', $order_id];
        $where[] = ['type', $type]; // 1订单收款 2还本付息 3费用报销  如果 重新给订单添加  收款记录，则要删除之前的收款记录
        FamiliesMoneyRecord::where($where)->delete();
        $money_sum = 0;
        if (count($pay_list) == 1) {
            $money_sum = $pay_list[0]['money'];
            if ($money_sum != $order->order_money) {
                $pay_list[0]['money'] = $order->order_money;
            }
        }
        foreach ($pay_list as $pay_dic) {
            $pay = new FamiliesMoneyRecord;
            $pay->order_id = $order_id;
            $pay->worker_id = $order->worker_id;
            $pay->branch_id = $order->branch_id;
            $pay->families_id = $pay_dic['families_id'];
            $pay->money =  $pay_dic['money'];
            $pay->type = $type; // 1订单收款 2还本付息 3费用报销
            $pay->status = $status; // 1审核中  2通过/待打款  3拒绝 4打款中 5已收款(已付款)
            $pay->course_money =  $pay_dic['course_money'] ?? 0;
            $pay->pay_type =  $pay_dic['pay_type'];
            $pay->real_time =  $pay_dic['real_time'] ?? $order->account_time;
            $pay->type =  1;
            $pay->save();
        }
    }
    /**
     * @description: 修改订单接口
     * @param {Request} $request
     * @return {*}
     */
    public function ChangeOrder(Request $request)
    {
        // 接参
        try {
            //去验证token值
            $tokenInfo = json_decode($this->verifyTokenLm(), true);
            //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
            if ($tokenInfo['code'] == 400) {
                return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
            }
            $worker_id = $tokenInfo['worker_id'];
            //接收前端传递过来的值
            $all = $request->all();
            if (!isset($all["order_id"])) {
                return LMReturn::Error('选择需要修改的订单', 300); //  300缺少必传参数
            }
            $order_id = $all["order_id"];
            $image_ids = $all['image_ids'] ?? [];
            // 到账银行部分
            $pay_list = $all['pay_list'] ?? [];
        } catch (\Throwable $th) {
            return LMReturn::Error('接参时发生错误', 'OC027');
        }
        try {
            $order = Order::find($order_id) ?? false;
            if (!$order) {
                return LMReturn::Error('要修改的订单不存在', 300); //  300缺少必传参数
            }
            $all['id'] = $order_id;
            unset($all['order_id']);
            $all['product_id'] = $all['product_id'] ?? $order->product_id;
            $product = Product::find($all['product_id']);
            //计算产品相关数据
            $order_money = $all['order_money'] ?? $order->order_money;
            $product_data = OrderController::calculateEndTime($all['valid_time'], $product, $order_money);
            $all['results_rate'] = $product_data['results_rate'];
            $all['results_money'] = $product_data['results_money'];
            $contract_end_date_int = strtotime($product_data['contract_end_date']);
            $valid_time_int = strtotime($all['valid_time']);
            if ($contract_end_date_int < $valid_time_int) {
                return LMReturn::Error('发生了不可预知的错误,请检查参数，如果无法解决，请联系技术支持', 'OCOS1');
            }
            $all['contract_end_date'] = $product_data['contract_end_date'];;
            $order_status = $all['order_status'] ?? false; // 如果传了只允许传2和-1，如果不是2或者-1,就报错 2是审核中 -1是草稿
            if ($order_status != '-1' && $order_status != '2') {
                return LMReturn::Error('您的订单存在风险', 'OC002');
            }
            $all['audit_step'] = '1'; //订单修改后，审核步骤，进入第一步
            if (isset($all['investment_way'])) {
                if ($all['investment_way'] == 3) {
                    $all['investment_way'] == 2;
                }
            }
        } catch (\Throwable $th) {
            return LMReturn::Error('处理参数时发生错误', 'OC028');
        }
        // 数据库数据修改
        try {
            DB::beginTransaction(); //开启事务
            $res = $order->update($all);
            OrderController::OrderPayList($pay_list,  $order, 1, 1);
            $order['order_id'] =  $order_id;
            // 插入订单变动记录
            OrderRecordController::InsertOrderModelRecord($order, $tokenInfo, '3');
            DB::commit(); //提交至数据库
        } catch (\Throwable $th) {
            DB::rollback(); //数据库回滚
            return LMReturn::Error('订单修改失败', 'OC009');
        }
        // 如果返回false，则是修改时报错，数据库回滚，返回错误信息// 处理图片
        if (!Utils::UpImage($image_ids, $order->images, $order_id, 3, $worker_id)) {
            return LMReturn::Error('添加修改图片出现错误其他信息已提交，请重新上传图片', 'BCC002');
        }
        return LMReturn::Success($order, '订单修改成功');
    }

    public function OrderListNew(Request $request)
    {
        try {
            //去验证token值
            $tokenInfo = json_decode($this->verifyTokenLm(), true);
            //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
            if ($tokenInfo['code'] == 400) {
                return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
            }
            //接收前端传递过来的值
            $all = $request->all();
            $where = $this->orderWhere($all);
            $worker_id = $tokenInfo['worker_id'];
            if (isset($all['worker_id'])) {
                $bmidList = [];
                $where[] = ["order.worker_id", $all['worker_id']];
            } else {
                if (isset($all['manage_bm'])) {
                    $bmidList = BranchController::queryBranchToWorkerID($worker_id, $all['manage_bm']);
                } else {
                    $bmidList = BranchController::queryBranchToWorkerID($worker_id);
                }
                if (count($bmidList) == 0) {
                    $where[] = ['order.worker_id', $worker_id];
                }
            }
            $UserWhereHas = [];
            if (isset($all['contact_manner'])) {
                $UserWhereHas[] = ['contact_manner', $all['contact_manner']];
            }
            if (isset($all['id_number'])) {
                $UserWhereHas[] = ['id_number', $all['id_number']];
            }
            $user_id_birthday = [];
            if (isset($all['birthday'])) {
                $user_id_birthday = json_decode(User::select('id')->where("birthday", 'like', '%' . $all['birthday'] . '%')->get(), true);
                $user_id_birthday = CommonFun::SelSqlArr('id', $user_id_birthday);
            }
            //查看具体部门的订单  管理部门和部门二选一（都传取branch_id），传管理部门是全部，传部门是部门下的数据
            if (isset($all['branch_id'])) {
                $where[] = ["order.branch_id", $all['branch_id']];
            }
            $pageSize = $all['size'] ?? 15;
            $user_id_list = [];
            if (isset($all['user_name'])) {
                $user_id_list = json_decode(User::select('id')
                    ->where("name", 'like', '%' . $all['user_name'] . '%')->get(), true);
                $user_id_list = CommonFun::SelSqlArr('id', $user_id_list);
            }
            if ($user_id_list == [] && $user_id_birthday == []) {
                $user_list_id = [];
            } elseif ($user_id_list == [] && $user_id_birthday != []) {
                $user_list_id = $user_id_birthday;
            } elseif ($user_id_list != [] && $user_id_birthday == []) {
                $user_list_id = $user_id_list;
            } else {
                $user_list_id = [];
                foreach ($user_id_list as $user_id) {
                    if (in_array($user_id, $user_id_birthday)) {
                        $user_list_id[] = $user_id;
                    }
                }
            }
            $product_list = [];
            if (isset($all['product_name'])) {
                $product_id_list = Product::select('id')->where("name", 'like', '%' . $all['product_name'] . '%')->get();
                if ($product_id_list) {
                    foreach ($product_id_list as $product_id) {
                        $product_list[] = $product_id['id'];
                    }
                }
            }
        } catch (\Throwable $th) {
            return LMReturn::Error('查询条件存在问题，请联系管理员', 'OC023');
        }

        try {
            $order_list = Order::with('branch')
                ->with('worker')
                ->with('user')
                ->with('families_money_records')
                // ->with('order_records')
                ->where($where)
                ->when(count($bmidList) > 0, function ($query) use ($bmidList) {
                    return $query->whereIn('order.branch_id', $bmidList);
                })
                ->when(isset($all['user_name']), function ($query) use ($user_list_id) {
                    return $query->whereIn('order.user_id', $user_list_id);
                })
                ->when(isset($all['product_name']), function ($query) use ($product_list) {
                    return $query->whereIn('order.product_id', $product_list);
                })
                ->when(isset($all['bank_card_num']), function ($query) use ($all) {
                    $bank_card_num = $all['bank_card_num'];
                    return $query->whereHas('bank_card', function ($q) use ($bank_card_num) {
                        $q->where('bank_num', $bank_card_num);
                    });
                })
                ->whereHas('user', function ($query) use ($UserWhereHas) {
                    $query->where($UserWhereHas);
                })
                ->when(isset($all['user_name']), function ($query) use ($all) {
                    $query->orderBy("order.contract_end_date", "desc");
                })
                ->orderBy("order.update_time", "desc")
                ->paginate($pageSize);
        } catch (\Throwable $th) {
            return LMReturn::Error('查询存在问题，请联系管理员', 'OC020');
        }
        try {
            // 返回前端需要的数据
            $res_order_list = OrderV2::collection($order_list);
            $return_datas = Utils::deal_page_resources($res_order_list, $order_list);
            return LMReturn::Success($return_datas);
        } catch (\Throwable $th) {
            return LMReturn::Error('数据存在问题，请联系管理员', 'OCOLN1');
        }
    }

    /**
     * @description: order 条件查询 条件构造
     * @param {Request} $request
     * @return array
     */
    public function orderWhere($all)
    {
        $where = [];
        //查询这个产品的订单
        if (isset($all['product_id'])) {
            $where[] = ["order.product_id", $all['product_id']];
        }
        // 合同号
        if (isset($all['contract_no'])) {
            $where[] = ['order.contract_no', $all['contract_no']];
        }
        // 签署时间
        if (isset($all['start_sign_time']) && isset($all['end_sign_time'])) {
            $where[] = ['order.sign_time', '>=', date('Y-m-d', strtotime($all['start_sign_time']))];
            $where[] = ['order.sign_time', '<=', date('Y-m-d', strtotime($all['end_sign_time']))];
        }
        // 起收益日期
        if (isset($all['start_valid_time']) && isset($all['end_valid_time'])) {
            $where[] = ['order.valid_time', '>=', date('Y-m-d', strtotime($all['start_valid_time']))];
            $where[] = ['order.valid_time', '<=', date('Y-m-d', strtotime($all['end_valid_time']))];
        }
        // 订单结束日期
        if (isset($all['start_contract_end_date']) && isset($all['end_contract_end_date'])) {
            $where[] = ['order.contract_end_date', '>=', date('Y-m-d', strtotime($all['start_contract_end_date']))];
            $where[] = ['order.contract_end_date', '<=', date('Y-m-d', strtotime($all['end_contract_end_date']))];
        }
        // 发送状态
        if (isset($all['sms_status'])) {
            if ($all['sms_status'] == 0) {
                $where[] = ['order.sms_status', 0];
            } else {
                $where[] = ['order.sms_status', '!=', 0];
            }
        }
        //查询这个人的订单
        if (isset($all['user_id'])) {
            $where[] = ["order.user_id", $all['user_id']];
        }
        //查看是初审还是复审
        if (isset($all['audit_step'])) {
            $where[] = ["order.audit_step", $all['audit_step']];
        }
        //查询订单状态  -1是草稿 1是待付款  2是审核中   3是待生效  4是已生效 5是拒绝  6是已结束
        if (isset($all['order_status'])) {
            $where[] = ["order.order_status", $all['order_status']];
        } else {
            $where[] = ["order.order_status", "!=", -1]; // 不能是草稿
            $where[] = ["order.order_status", "!=", 5]; // 不能是已拒绝订单
            // $where[] = ["order.order_status", "!=", 3]; // 不能是待生效
            $where[] = ["order.order_status", "!=", 2]; // 不能是审核中
            $where[] = ["order.order_status", "!=", 1]; // 不能是待付款
            $where[] = ["order.order_status", "!=", 7]; // 不能是废弃

        }

        if (isset($all['worker_id'])) {
            $where[] = ["order.worker_id", $all['worker_id']];
        }

        return $where;
    }

    /**
     * @description: 订单列表接口
     * @param {Request} $request
     * @return {*}
     */
    public function OrderList(Request $request)
    {
        try {
            //去验证token值
            $tokenInfo = json_decode($this->verifyTokenLm(), true);
            //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
            if ($tokenInfo['code'] == 400) {
                return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
            }
            //接收前端传递过来的值
            $all = $request->all();
            $where = $this->orderWhere($all);
            $worker_id = $tokenInfo['worker_id'];
            if (isset($all['manage_bm'])) {
                $bmidList = BranchController::queryBranchToWorkerID($worker_id, $all['manage_bm']);
            } else {
                $bmidList = BranchController::queryBranchToWorkerID($worker_id);
            }
            if (count($bmidList) == 0) {
                $where[] = ['order.worker_id', $tokenInfo['worker_id']];
            }
            //查看具体部门的订单  管理部门和部门二选一（都传取branch_id），传管理部门是全部，传部门是部门下的数据
            if (isset($all['branch_id'])) {
                $where[] = ["order.branch_id", $all['branch_id']];
            }
            $pageSize = isset($all['size']) ? $all['size'] : 15;
            $user_id_list = [];
            if (isset($all['user_name'])) {
                $user_id_list = json_decode(User::select('id')
                    ->where("name", 'like', '%' . $all['user_name'] . '%')->get(), true);
                $user_id_list = CommonFun::SelSqlArr('id', $user_id_list);
            }
        } catch (\Throwable $th) {
            return LMReturn::Error('查询条件存在问题，请联系管理员', 'OC023');
        }

        try {
            $order_list = Order::where($where)
                ->with('bank_card')
                ->with('bank_card.bank')
                ->with('worker')
                ->with('user')
                ->with('branch')
                ->with('product')
                ->with('working_family')
                ->with('product.product_class')
                ->with('record_worker')
                ->with('order_records')
                ->with('families_money_records.working_family')
                ->when(count($bmidList) > 0, function ($query) use ($bmidList) {
                    return $query->whereIn('order.branch_id', $bmidList);
                })
                ->when(isset($all['user_name']), function ($query) use ($user_id_list) {
                    return $query->whereIn('order.user_id', $user_id_list);
                })
                ->orderBy("order.update_time", "desc")
                ->paginate($pageSize);
        } catch (\Throwable $th) {
            return LMReturn::Error('查询存在问题，请联系管理员', 'OC029');
        }

        try {
            // 返回前端需要的数据
            $data_order_list = json_decode(json_encode($order_list), true);
            $res_order_list = ResourcesOrder::collection($order_list);
            $return_datas['current_page'] = $data_order_list['current_page'];
            $return_datas['from'] = $data_order_list['from'];
            $return_datas['last_page'] = $data_order_list['last_page'];
            $return_datas['per_page'] = $data_order_list['per_page'];
            $return_datas['to'] = $data_order_list['to'];
            $return_datas['total'] = $data_order_list['total'];
            $return_datas['data'] = $res_order_list;
            return LMReturn::Success($return_datas);
        } catch (\Throwable $th) {
            return LMReturn::Error('数据存在问题，请联系管理员', 'OC022');
        }
    }

    public function OrderDetail(Request $request)
    {
        try {
            //去验证token值
            $tokenInfo = json_decode($this->verifyTokenLm(), true);
            //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
            if ($tokenInfo['code'] == 400) {
                return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
            }
            //接收前端传递过来的值
            $all = $request->all();
            $order_id = $all['order_id'];
        } catch (\Throwable $th) {
            return LMReturn::Error('传参存在问题', 'OC024');
        }

//        try {
            $type = 1;
            $order = Order::where('id', $order_id)
                ->with('bank_card.images')
                ->with('bank_card.bank')
                ->with('worker.images')
                ->with('worker.roles')
                ->with('worker.branches')
                ->with('worker.branchesManage')
                ->with('record_worker')
                ->with('user.images')
                ->with('user.pro')
                ->with('user.city')
                ->with('user.area')
                ->with('branch')
                ->with('working_family')
                ->with('product.product_class')
                ->with('order_records')
                ->with('interest_records')
                ->with('images')
                ->with('families_money_records.working_family')
                ->with('fdd_records')
                ->first();
            $orderDetail = OrderDetail::collection([$order]);
            return LMReturn::Success($orderDetail[0]);
//        } catch (\Throwable $th) {
//            return LMReturn::Error('查找订单失败', 'OC025');
//        }
    }


    // 删除待修改订单和草稿
    public function OrderDelete(Request $request)
    {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $all = $request->all();
        if (isset($all['order_id'])) {
            $order_id = $all['order_id'];
        } else {
            return LMReturn::Error('未传入订单id');
        }
        $can_dele_list = [-1, 5, 7];
        $order = Order::find($order_id);
        if ($order) {
            try {
                if (in_array($order['order_status'], $can_dele_list)) {
                    $images = Image::where('order_id', $order['id'])->whereIn('img_type', [3, 4])->get();
                    if ($images) {
                        foreach ($images as $image) {
                            docutils::del_img($image['img_path']);
                        }
                    }
                    $order->delete();
                    return LMReturn::Success();
                } else {
                    return LMReturn::Error('非待修改订单或草稿,无法删除');
                }
            } catch (\Throwable $th) {
                return LMReturn::Error('无法删除');
            }
        } else {
            return LMReturn::Error('未能找到该订单id');
        }
    }



    /**
     * @description: 传入生效时间，产品，计算到期时间
     * @param {*}
     * @return {*}
     */
    public static function calculateEndTime($valid_time, $product, $order_money = 0)
    {
        // 计算合同终止时间
        $year = date("Y", strtotime($valid_time));
        $longTime = $product->long_time; // 产品周期

        $month = date("m", strtotime($valid_time)) + $longTime;
        $nm = intval($month / 12); // 取整
        $month = intval($month % 12); // 取整
        if ($month < 10) {
            $month = '0' . $month;
        }
        $year = $year + $nm;
        $day = date("d", strtotime($valid_time));
        $daynum = date("t", strtotime($year . "-" . $month));
        if ($day <= $daynum) {
            $next_date = $year . "-" . $month . "-" . $day;
        } else {
            $next_date = $year . "-" . $month . "-" . $daynum;
        }
        $next_date = strtotime($next_date) - 86400;
        // 订单结束时间
        $orderEndTime = date("Y-m-d", $next_date);
        // 年化金额   和 年化比例
        if ($product->year_type == 1) { //年化方式 1是年化比例 2是固定年化
            $results_rate = $product->results_rate;
            $results_money = round($results_rate * $order_money / 100, 2);
        } elseif ($product->year_type == 2) { // 固定年化
            $results_rate = $product->results_rate;
            $results_money = $product->results_rate;
        } else { // 不知道就是0
            $results_rate = 0;
            $results_money = 0;
        }
        $product_data['contract_end_date'] = $orderEndTime;
        $product_data['results_rate'] = $results_rate;
        $product_data['results_money'] = $results_money;
        return $product_data;
    }
}
